import { createRouter, createWebHistory } from 'vue-router'
import NotFound from '@/views/error/NotFound.vue'
import StartView from '@/views/page/StartView.vue'
import MainLayout from '@/layouts/MainLayout.vue'
import AiChatView from '@/views/page/ai/AiChatView.vue'  
import FileView from '@/views/page/create/FileView.vue'
import RepositoryView from '@/views/page/create/RepositoryView.vue'
import AccountLoginView from '@/views/page/user/account/AccountLoginView.vue'
import AccountRegisterView from '@/views/page/user/account/AccountRegisterView.vue'
import AuthView from '@/views/page/AuthView.vue'
import { useUserStore } from '@/store/user'

const routes = [
    {
        path: '/',
        component: MainLayout,
        children: [
            {
                path: '/start/',
                name: 'start',
                component: StartView,
            },
        ],
        meta: {
            requestAuth: true, // 需要登录
        },
    },
    {
        path: '/auth/',
        name: 'auth',
        component: AuthView,
        meta: {
            requestAuth: false, 
        },
    },
    {
        path: '/aichat/',
        name: 'aichat',
        component: AiChatView,
        meta: {
            requestAuth: true, // 需要登录
        },
    },
    {
        path: '/file/:id',
        name: 'file',
        component:FileView,
        meta: {
            requestAuth: false, // 需要登录
        },
    },
    {
        path:'/repository/:id',
        name:'repository',
        component:RepositoryView,
        meta:{
            requestAuth:true,
        }
    },
    {
        path: '/login/',
        name: 'login',
        component:AccountLoginView,
        meta: {
            requestAuth: false, // 不需要登录
        },

    },
    {
        path: '/register/',
        name: 'register',
        component: AccountRegisterView,
        meta: {
            requestAuth: false, // 不需要登录
        },
    },
   {
        path: '/404/',
        name: 'notfound',
        component: NotFound,
    },
    {
        path: '/:catchAll(.*)',
        redirect: '/404/',
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    const store = useUserStore()
    // 路由守卫，检查用户是否登录
    if (to.meta.requestAuth && !store.is_login) {
        next({ name: 'login' })
    } else {
        next() // 确保一定要调用 next()
    }
})
export default router
